package me.zhengjie.service.impl;

import io.minio.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.MinioConfig;
import me.zhengjie.service.MinioService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {
    private final MinioClient minioClient;
    private final MinioConfig minioConfig;

    @PostConstruct
    public void init() throws Exception {
        // 检查 bucket 是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(minioConfig.getBucketName())
                .build());

        // 如果不存在则创建
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .build());
        }

        // 设置 bucket 策略为公共读
        String policy = String.format(
                "{" +
                        "\"Version\": \"2012-10-17\"," +
                        "\"Statement\": [" +
                        "{" +
                        "\"Effect\": \"Allow\"," +
                        "\"Principal\": {\"AWS\": [\"*\"]}," +
                        "\"Action\": [\"s3:GetObject\"]," +
                        "\"Resource\": [\"arn:aws:s3:::%s/*\"]" +
                        "}" +
                        "]" +
                        "}", minioConfig.getBucketName());

        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                .bucket(minioConfig.getBucketName())
                .config(policy)
                .build());
    }

    public String uploadFile(MultipartFile file) throws Exception {
        // 检查文件
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replaceAll("-", "")
                + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传文件
        try (InputStream inputStream = file.getInputStream()) {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .stream(inputStream, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
        }
        // ignore

        // 返回文件访问路径
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }
}